package com.huanying.sales.apartmentshape;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huanying.framework.BaseDao;
import com.huanying.framework.PageBean;
import com.huanying.sales.project.Project;
import com.huanying.sales.region.Region;

@Service
public class ApartmentShapeServiceImpl implements ApartmentShapeService {
	
	@Autowired
	private BaseDao dao;

	@Override
	public ApartmentShape add(ApartmentShape as) throws Exception {
		ApartmentShape u = (ApartmentShape)dao.save(as);
		return u;
	}

	@Override
	public void update(ApartmentShape as) throws Exception {
		dao.update(as);
	}

	@Override
	public ApartmentShape get(int id) throws Exception {
		ApartmentShape unit = (ApartmentShape)dao.load(ApartmentShape.class, id);
		return unit;
	}

	@Override
	public PageBean findApartmentShape(int pageSize, int page) throws Exception {
		String hql="from ApartmentShape where status=1";
		
		int allRow = dao.queryAllRowCount(hql, null);
		int totalPage = PageBean.countTotalPage(pageSize, allRow);
		final int offset = PageBean.countOffset(pageSize, page);
	    final int currentPage = PageBean.countCurrentPage(page);
	    List list = dao.queryForPageAndParams(hql,null, offset, pageSize);
	    
	    //把分页信息保存到Bean中
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(pageSize);    
        pageBean.setCurrentPage(currentPage);
        pageBean.setAllRow(allRow);
        pageBean.setTotalPage(totalPage);
        pageBean.setList(list);
        pageBean.init();
		
		return pageBean;
	}

	@Override
	public List<ApartmentShape> findApartmentShapeByUnitId(int unit_id) throws Exception {
		Session session = dao.getSession();
		String hql = "from ApartmentShape where project_id in (select distinct(r.project_id) from Unit u,Building b,Region r where u.building_id=b.id and b.region_id=r.id and u.id=?)";
		Query query = session.createQuery(hql);
		query.setInteger(0, unit_id);
		List<ApartmentShape> l = query.list();
		return l;
	}

	@Override
	public List<ApartmentShape> findApartmentShapeByProjectId(int project_id)
			throws Exception {
		String hql = "from ApartmentShape where status=1 and project_id=:project_id";
		ApartmentShape a = new ApartmentShape();
		a.setProject_id(project_id);
		List apartmentShapes = dao.exculeHql(hql, a);
		return apartmentShapes;
	}

	@Override
	public void delete(ApartmentShape as) throws Exception {
		dao.delete(as);
	}
	
	

}
